package bar.dark.lee.beforesms;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.CalendarPickerDialog;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.common.SuperInterface;
import bar.dark.lee.insert.BalanceQuery;
import bar.dark.lee.setting.sms.InputData;
import bar.dark.lee.setting.sms.Parser;
import bar.dark.lee.setting.sms.SMSData;
import bar.dark.lee.setting.sms.SmsLoadInbox;

public class BeforeSmsListActivity extends SuperActivity implements SuperInterface {

	public static final int REQUEST_BEFORESMS_ADD = 0;
	
	private DBSQLite dbSql;
	
	private ListView listViewBeforesms;
	private Button btnInsert;
	
	private View resultView;
	
	private View viewStartDate;
	private TextView textStartDate;
	
	private View viewEndDate;
	private TextView textEndDate;
	
	private ArrayList<AutoSmsData> autosmsList;
	private ArrayList<BeforeSmsData> beforesmsList;
	
	private int inMoneyColor;
	private int outMoneyColor;
	private int postMoneyColor;
	private int cashDrawingColor;
	
	private int startYear;
	private int startMonth;
	private int startDay;
	
	private int endYear;
	private int endMonth;
	private int endDay;
	
	private boolean autosmsFlag = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.beforesms_list_activity);
		
		dbSql = DBSQLite.getInstance(superContext);
		
		setTitle("문자 한번에 입력");
		setGoneTipButton();
		
		setFindView();
		setClickListener();
		
		Calendar cal = Calendar.getInstance();
		startYear = cal.get(Calendar.YEAR);
		startMonth = cal.get(Calendar.MONTH);
		startDay = cal.get(Calendar.DAY_OF_MONTH);
		endYear = startYear;
		endMonth = startMonth;
		endDay = startDay;
		
		textStartDate.setText(BDUtil.getDate(startYear, (startMonth+1), startDay));
		
		textEndDate.setText(BDUtil.getDate(endYear, (endMonth+1), endDay));
		
		final SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		final SharedPreferences.Editor editor = pref.edit();
    	int flag = pref.getInt(BDConstents.BEFORE_SMS_FIRST_START, 0);
		if (flag == 0)
		{
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setTitle("알림");
			dialog.setMessage("1.문자 여러개를 한번에 입력 할 수 있습니다.\n" +
					"2.입금/출금/결제 문자 만 가능합니다.\n" +
					"3.문자자동화에 등록된 통장/카드 만 가능합니다.\n" +
					"4.문자자동화를 자동/질문 으로 해놓지 않아도 가능합니다.\n" +
					"(즉, 문자자동화에 통장/카드를 등록만 해두시고 '안함'으로 설정해두셔도 됩니다.)\n" +
					"5.검색되는 문자들을 꼭 확인해보고 입력하세요.");
			dialog.setCancelable(false);
			dialog.setPositiveButton("다시 보지 않음", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialogg, int which)
				{
					editor.putInt(BDConstents.BEFORE_SMS_FIRST_START, 1);
					editor.commit();
					dialogg.dismiss();
					new ShowDialog().execute(BDUtil.asyncFlag, 0);
				}
			});
			
			dialog.setNegativeButton("확인", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					dialog.dismiss();
					new ShowDialog().execute(BDUtil.asyncFlag, 0);
				}
			});
			
			dialog.show();
		}
		else
		{
			new ShowDialog().execute(BDUtil.asyncFlag, 0);
		}
	}
	
	@Override
	public void setFindView() {
		
		listViewBeforesms = (ListView)findViewById(R.id.beforesmsListView);
		btnInsert = (Button)findViewById(R.id.beforesmsListInsertButton);
		
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
		
		viewStartDate = findViewById(R.id.beforesmsStartDateView);
		textStartDate = (TextView) findViewById(R.id.beforesmsStartDateTextView);
		
		viewEndDate = findViewById(R.id.beforesmsEndDateView);
		textEndDate = (TextView) findViewById(R.id.beforesmsEndDateTextView);
		
		inMoneyColor = getResources().getColor(R.color.inmoney);
		outMoneyColor = getResources().getColor(R.color.outmoney);
		postMoneyColor = getResources().getColor(R.color.postmoney);
		cashDrawingColor = getResources().getColor(R.color.cashdrawingmoney);
	}
	
	private class AutoSmsData
	{
		String address;
		String messageCardName;
		String parserNumber;
		String linkCardName;
		String linkCardType;
		
		public String getAddress() {
			return address;
		}
		public void setAddress(String address) {
			this.address = address;
		}
		public String getMessageCardName() {
			return messageCardName;
		}
		public void setMessageCardName(String messageCardName) {
			this.messageCardName = messageCardName;
		}
		public String getParserNumber() {
			return parserNumber;
		}
		public void setParserNumber(String parserNumber) {
			this.parserNumber = parserNumber;
		}
		public String getLinkCardName() {
			return linkCardName;
		}
		public void setLinkCardName(String linkCardName) {
			this.linkCardName = linkCardName;
		}
		public String getLinkCardType() {
			return linkCardType;
		}
		public void setLinkCardType(String linkCardType) {
			this.linkCardType = linkCardType;
		}
	}
	
	private class BeforeSmsData
	{
		String moneyType;
		String type;
		String date;
		String name;
		String memo;
		String inmoney;
		String outmoney;
		String postmoney;

		public String getMoneyType() {
			return moneyType;
		}
		public void setMoneyType(String moneyType) {
			this.moneyType = moneyType;
		}
		public String getType() {
			return type;
		}
		public void setType(String type) {
			this.type = type;
		}
		public String getDate() {
			return date;
		}
		public void setDate(String date) {
			this.date = date;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getMemo() {
			return memo;
		}
		public void setMemo(String memo) {
			this.memo = memo;
		}
		public String getInmoney() {
			return inmoney;
		}
		public void setInmoney(String inmoney) {
			this.inmoney = inmoney;
		}
		public String getOutmoney() {
			return outmoney;
		}
		public void setOutmoney(String outmoney) {
			this.outmoney = outmoney;
		}
		public String getPostmoney() {
			return postmoney;
		}
		public void setPostmoney(String postmoney) {
			this.postmoney = postmoney;
		}
	}
	
	@Override
	public void setDataSetting() {
		
		autosmsList = new ArrayList<AutoSmsData>();
		String query = "SELECT * from sms;";
		dbSql.selectMapTile(superContext, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				c.moveToFirst();
				
				if (count != 0)
				{
					int addressIndex = c.getColumnIndex("address");
					int messageCardNameIndex = c.getColumnIndex("messagecardname");
					int parserIndex = c.getColumnIndex("parser");
					int linkCardNameIndex = c.getColumnIndex("linkcardname");
					int linkCardTypeIndex = c.getColumnIndex("linkcardtype");
					
					for (int i = 0; i < count; i++)
					{
						AutoSmsData data = new AutoSmsData();
						
						data.setAddress(c.getString(addressIndex));
						data.setMessageCardName(c.getString(messageCardNameIndex));
						data.setParserNumber(c.getString(parserIndex));
						data.setLinkCardName(c.getString(linkCardNameIndex));
						data.setLinkCardType(c.getString(linkCardTypeIndex));
						
						autosmsList.add(data);
						
						c.moveToNext();
					}
				}
			}
		});
		
		if (autosmsList.size() == 0)
		{
			autosmsFlag = false;
			return;
		}
		
		beforesmsList = new ArrayList<BeforeSmsData>();
		
		SmsLoadInbox inbox = new SmsLoadInbox(superContext);
		ArrayList<SMSData> totalsmsList = inbox.loadSMS();
		ArrayList<SMSData> searchsmsList = new ArrayList<SMSData>();
		
		int first = Integer.parseInt(BDUtil.getDateDB(startYear, startMonth+1, startDay));
		int last = Integer.parseInt(BDUtil.getDateDB(endYear, endMonth+1, endDay));
		
		boolean autoFlag = false;
		for (int i=0; i<totalsmsList.size(); i++)
		{
			for (int j=0; j<autosmsList.size(); j++)
			{
				if (totalsmsList.get(i).getAddress().equalsIgnoreCase(autosmsList.get(j).getAddress()))
				{
					autoFlag = true;
				}
			}
			
			if (autoFlag)
			{
				SMSData data = totalsmsList.get(i);
				if (first <= Integer.parseInt(data.getDate()) && Integer.parseInt(data.getDate()) <= last)
				{
					searchsmsList.add(data);
				}
				
				autoFlag = false;
			}
		}
		
		// 날짜별 문자와 문자자동화, 파서 비교후
		
		for (int i=0; i<searchsmsList.size(); i++)
		{
			Parser parser = null;
			try {
				parser = new Parser(searchsmsList.get(i).getBody());
			} catch (Exception e)
			{
				//Toast.makeText(superContext, "문제가 생겨 누락된 문자가 있습니다. 누락된 문자가 확인되면 개발자에게 메일을 보내주세요.", Toast.LENGTH_SHORT).show();
				//return;
			} finally
			{
				if (parser == null)
				{
					//Toast.makeText(superContext, "문자 분석중에 문제가 생겼습니다. 개발자에게 메일을 보내주세요.", Toast.LENGTH_SHORT).show();
					return;
				}
			}
			
			InputData data = new InputData();
			data = parser.messageParsing();
			
			if (data == null || data.getName() == null || data.getDate() == null || data.getMemo1() == null || data.getMoney() == null)
			{
				continue;
			}
			
			int smsType = parser.getSmsType();
			boolean flagATM = parser.getFlagATM();
			
			if (smsType == BDConstents.OUT_ATM_SMS || smsType == BDConstents.IN_ATM_SMS)
			{
				continue;
			}
			
			for (int j=0; j<autosmsList.size(); j++)
			{
				if (data.getName().equalsIgnoreCase(autosmsList.get(j).getMessageCardName()))
				{
					AutoSmsData autosmsData = autosmsList.get(j);
					
					BeforeSmsData beforesmsData = new BeforeSmsData();
					beforesmsData.setMoneyType(autosmsData.getLinkCardType());
					beforesmsData.setDate(data.getDate());
					beforesmsData.setName(autosmsData.getLinkCardName());
					beforesmsData.setMemo(data.getMemo1());
					
					if (autosmsData.getLinkCardType().equalsIgnoreCase("3"))
					{
						autosmsData.setLinkCardType(BDConstents.CREDIT_TYPE);
					}
					else if (autosmsData.getLinkCardType().equalsIgnoreCase("4"))
					{
						autosmsData.setLinkCardType(BDConstents.CHECK_TYPE);
					}
					else if (autosmsData.getLinkCardType().equalsIgnoreCase("1"))
					{
						autosmsData.setLinkCardType(BDConstents.BANK_TYPE);
					}
					
					// 신용카드
					if (autosmsData.getLinkCardType().equalsIgnoreCase(BDConstents.CREDIT_TYPE))
					{
						if (smsType == BDConstents.OUT_ATM_SMS)
						{
							beforesmsData.setType(BDConstents.INOUT_TYPE);
							beforesmsData.setPostmoney(data.getMoney());
							beforesmsData.setInmoney(data.getMoney());
							beforesmsData.setOutmoney("0");
						}
						else
						{
							beforesmsData.setType(BDConstents.CREDIT_TYPE);
							beforesmsData.setPostmoney(data.getMoney());
							beforesmsData.setInmoney("0");
							beforesmsData.setOutmoney("0");
						}
					}
					// 체크카드
					else if (autosmsData.getLinkCardType().equalsIgnoreCase(BDConstents.CHECK_TYPE))
					{
						if (smsType == BDConstents.OUT_ATM_SMS)
						{
							beforesmsData.setType(BDConstents.INOUT_TYPE);
							beforesmsData.setPostmoney("0");
							beforesmsData.setInmoney(data.getMoney());
							beforesmsData.setOutmoney(data.getMoney());
						}
						else if (smsType == BDConstents.IN_ATM_SMS)
						{
							beforesmsData.setType(BDConstents.OUTIN_TYPE);
							beforesmsData.setPostmoney("0");
							beforesmsData.setInmoney(data.getMoney());
							beforesmsData.setOutmoney(data.getMoney());
						}
						else if (smsType == BDConstents.IN_SMS)
						{
							beforesmsData.setType(BDConstents.CHECK_TYPE);
							beforesmsData.setPostmoney("0");
							beforesmsData.setInmoney(data.getMoney());
							beforesmsData.setOutmoney("0");
						}
						else
						{
							beforesmsData.setType(BDConstents.CHECK_TYPE);
							beforesmsData.setPostmoney("0");
							beforesmsData.setInmoney("0");
							beforesmsData.setOutmoney(data.getMoney());
						}
						
					}
					// 통장
					else if (autosmsData.getLinkCardType().equalsIgnoreCase(BDConstents.BANK_TYPE))
					{
						if (smsType == BDConstents.OUT_ATM_SMS)
						{
							beforesmsData.setType(BDConstents.INOUT_TYPE);
							beforesmsData.setPostmoney("0");
							beforesmsData.setInmoney(data.getMoney());
							beforesmsData.setOutmoney(data.getMoney());
						}
						else if (smsType == BDConstents.IN_ATM_SMS)
						{
							beforesmsData.setType(BDConstents.OUTIN_TYPE);
							beforesmsData.setPostmoney("0");
							beforesmsData.setInmoney(data.getMoney());
							beforesmsData.setOutmoney(data.getMoney());
						}
						else if (smsType == BDConstents.IN_SMS)
						{
							beforesmsData.setType(BDConstents.BANK_TYPE);
							beforesmsData.setPostmoney("0");
							beforesmsData.setInmoney(data.getMoney());
							beforesmsData.setOutmoney("0");
						}
						else if (smsType == BDConstents.OUT_SMS)
						{
							beforesmsData.setType(BDConstents.BANK_TYPE);
							beforesmsData.setPostmoney("0");
							beforesmsData.setInmoney("0");
							beforesmsData.setOutmoney(data.getMoney());
						}
					}
					
					beforesmsData.setMoneyType(autosmsData.getLinkCardType());
					
					beforesmsList.add(beforesmsData);
					
					break;
				}
			}
		}
	}

	@Override
	public void setClickListener() {
		
		viewStartDate.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
					@Override
					public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
						
						String startDate = BDUtil.getDateDB(year, monthOfYear+1, dayOfMonth);
						String endDate = BDUtil.getDateDB(endYear, endMonth+1, endDay);
						
						if (Integer.parseInt(startDate) > Integer.parseInt(endDate))
						{
							BDUtil.showToast(superContext, "시작날짜 보다 종료날짜가 작을 수는 없습니다.");
							return;
						}
						
						textStartDate.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
						
						startYear = year;
						startMonth = monthOfYear;
						startDay = dayOfMonth;
						
						new ShowDialog().execute(BDUtil.asyncFlag, 0);
						
					}
				}, startYear, startMonth, startDay);
				
				cpd.show();
			}
		});
		
		viewEndDate.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				
				CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
					@Override
					public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
						
						String endDate = BDUtil.getDateDB(year, monthOfYear+1, dayOfMonth);
						String startDate = BDUtil.getDateDB(startYear, startMonth+1, startDay);
						
						if (Integer.parseInt(startDate) > Integer.parseInt(endDate))
						{
							BDUtil.showToast(superContext, "시작날짜 보다 종료날짜가 작을 수는 없습니다.");
							return;
						}
						
						textEndDate.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
						
						endYear = year;
						endMonth = monthOfYear;
						endDay = dayOfMonth;
						
						new ShowDialog().execute(BDUtil.asyncFlag, 0);
						
					}
				}, endYear, endMonth, endDay);
				
				cpd.show();
			}
		});
		
		btnInsert.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new ShowDialog().execute(BDUtil.asyncFlag, 1);
			}
		});
	}
	
	private int linkId = -1;
	private void insertInOutTable()
	{
		for (int i=0; i<beforesmsList.size(); i++)
		{
			final BeforeSmsData beforesmsData = beforesmsList.get(i);
			
			//신용카드			
			if (beforesmsData.getMoneyType() == BDConstents.CREDIT_TYPE)
			{
				// 현금출금
				if (beforesmsData.getType() == BDConstents.INOUT_TYPE)
				{
//					dbSql.selectMapTile(superContext, "SELECT id, outmoney FROM credit_card WHERE name = '" 
//							+ beforesmsData.getName() + "';", new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getPostmoney()));
//							int id = -1;
//							
//							int idIndex = c.getColumnIndex("id");
//							int moneyIndex = c.getColumnIndex("outmoney");
//							
//							c.moveToFirst();
//							BigDecimal dbMoney = BigDecimal.ZERO;
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								id = c.getInt(idIndex);
//								dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
//								c.moveToNext();
//							}
//							
//							dbMoney = dbMoney.add(tempMoney);
//							
//							if (id > -1)
//							{
//								HashMap<String, String> map = new HashMap<String, String>();
//								map.put("outmoney", dbMoney.toString());
//								String [] whereArgs = new String[]{id + ""};
//								dbSql.update(superContext, "credit_card", map, "id = ?", whereArgs);
//							}
//						}
//					});
//					
//					dbSql.selectMapTile(this, "SELECT money FROM real_money", new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getPostmoney()));
//							int moneyIndex = c.getColumnIndex("money");
//							
//							c.moveToFirst();
//							BigDecimal dbMoney = BigDecimal.ZERO;
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
//								c.moveToNext();
//							}
//							
//							dbMoney = dbMoney.add(tempMoney);
//							
//							HashMap<String, String> map = new HashMap<String, String>();
//							map.put("money", dbMoney.toString());
//							dbSql.update(superContext, "real_money", map, null, null);
//						}
//					});
				}
				else
				{
					dbSql.selectMapTile(this, "SELECT id, outmoney FROM credit_card WHERE name = '" 
							+ BDUtil.getApostrophe(beforesmsData.getName()) + "';", new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getPostmoney()));
							int id = -1;
							int idIndex = c.getColumnIndex("id");
							int moneyIndex = c.getColumnIndex("outmoney");
							
							c.moveToFirst();
							BigDecimal money = BigDecimal.ZERO;
							for (int i = 0; i < c.getCount(); i++)
							{
								id = c.getInt(idIndex);
								money = money.add(new BigDecimal(c.getString(moneyIndex)));
								c.moveToNext();
							}
							
							money = money.add(tempMoney);
							
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("outmoney", money.toString());
							String [] whereArgs = new String[]{id + ""};
							dbSql.update(superContext, "credit_card", map, "id = ?", whereArgs);
						}
					});
				}
			}
			else if (beforesmsData.getMoneyType() == BDConstents.CHECK_TYPE)
			{
				// 체크카드 현금입금
				if (beforesmsData.getType() == BDConstents.OUTIN_TYPE)
				{
//					dbSql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '" 
//							+ beforesmsData.getName() + "';", new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							linkId = -1;
//							int banklinkIndex = c.getColumnIndex("banklink");
//							
//							c.moveToFirst();
//							
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								linkId = c.getInt(banklinkIndex);
//								c.moveToNext();
//							}
//							
//							if (linkId > -1)
//							{
//								dbSql.selectMapTile(superContext, "SELECT money FROM bankbook WHERE id = " + linkId, new ParseSelectData()
//								{
//									@Override
//									public void resultData(Cursor c)
//									{
//										BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getInmoney()));
//										
//										int moneyIndex = c.getColumnIndex("money");
//										
//										c.moveToFirst();
//										BigDecimal dbMoney = BigDecimal.ZERO;
//										for (int i = 0; i < c.getCount(); i++)
//										{
//											dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
//											c.moveToNext();
//										}
//										
//										dbMoney = dbMoney.add(tempMoney);
//										
//										HashMap<String, String> map = new HashMap<String, String>();
//										map.put("money", dbMoney.toString());
//										String [] whereArgs = new String[]{linkId + ""};
//										dbSql.update(superContext, "bankbook", map, "id = ?", whereArgs);
//									}
//								});
//							}
//						}
//					});
//					
//					dbSql.selectMapTile(this, "SELECT money FROM real_money", new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getOutmoney()));
//							int moneyIndex = c.getColumnIndex("money");
//							
//							c.moveToFirst();
//							BigDecimal dbMoney = BigDecimal.ZERO;
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
//								c.moveToNext();
//							}
//							
//							dbMoney = dbMoney.subtract(tempMoney);
//							
//							HashMap<String, String> map = new HashMap<String, String>();
//							map.put("money", dbMoney.toString());
//							dbSql.update(superContext, "real_money", map, null, null);
//						}
//					});
				}
				// 체크카드 현금출금
				else if (beforesmsData.getType() == BDConstents.INOUT_TYPE)
				{
//					dbSql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '" 
//							+ beforesmsData.getName() + "';", new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							linkId = -1;
//							int banklinkIndex = c.getColumnIndex("banklink");
//							
//							c.moveToFirst();
//							
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								linkId = c.getInt(banklinkIndex);
//								c.moveToNext();
//							}
//							
//							if (linkId > -1)
//							{
//								dbSql.selectMapTile(superContext, "SELECT money FROM bankbook WHERE id = " + linkId, new ParseSelectData()
//								{
//									@Override
//									public void resultData(Cursor c)
//									{
//										BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getOutmoney()));
//										
//										int moneyIndex = c.getColumnIndex("money");
//										
//										c.moveToFirst();
//										BigDecimal dbMoney = BigDecimal.ZERO;
//										for (int i = 0; i < c.getCount(); i++)
//										{
//											dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
//											c.moveToNext();
//										}
//										
//										dbMoney = dbMoney.subtract(tempMoney);
//										
//										HashMap<String, String> map = new HashMap<String, String>();
//										map.put("money", dbMoney.toString());
//										String [] whereArgs = new String[]{linkId + ""};
//										dbSql.update(superContext, "bankbook", map, "id = ?", whereArgs);
//									}
//								});
//							}
//						}
//					});
//					
//					dbSql.selectMapTile(this, "SELECT money FROM real_money", new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getInmoney()));
//							int moneyIndex = c.getColumnIndex("money");
//							
//							c.moveToFirst();
//							BigDecimal dbMoney = BigDecimal.ZERO;
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
//								c.moveToNext();
//							}
//							
//							dbMoney = dbMoney.add(tempMoney);
//							
//							HashMap<String, String> map = new HashMap<String, String>();
//							map.put("money", dbMoney.toString());
//							dbSql.update(superContext, "real_money", map, null, null);
//						}
//					});
				}
				else
				{
					// 체크카드 입금
					if (beforesmsData.getOutmoney().equalsIgnoreCase("0"))
					{
						dbSql.selectMapTile(superContext, "SELECT banklink FROM check_card WHERE name = '" 
								+ BDUtil.getApostrophe(beforesmsData.getName()) + "';", new ParseSelectData()
						{
							@Override
							public void resultData(Cursor c)
							{
								linkId = -1;
								
								int banklinkIndex = c.getColumnIndex("banklink");
								
								c.moveToFirst();
								
								for (int i = 0; i < c.getCount(); i++)
								{
									linkId = c.getInt(banklinkIndex);
									c.moveToNext();
								}
							}
						});
						
						if (linkId > -1)
						{
							dbSql.selectMapTile(superContext, "SELECT money FROM bankbook WHERE id = " + linkId + ";", new ParseSelectData()
							{
								@Override
								public void resultData(Cursor c)
								{
									BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getInmoney()));
									
									int moneyIndex = c.getColumnIndex("money");
									
									c.moveToFirst();
									BigDecimal money = BigDecimal.ZERO;
									for (int i = 0; i < c.getCount(); i++)
									{
										money = money.add(new BigDecimal(c.getString(moneyIndex)));
										c.moveToNext();
									}
									
									money = money.add(tempMoney);
									
									HashMap<String, String> map = new HashMap<String, String>();
									map.put("money", money.toString());
									String [] whereArgs = new String[]{linkId + ""};
									dbSql.update(superContext, "bankbook", map, "id = ?", whereArgs);
								}
							});
						}
					}
					// 체크카드 출금
					else
					{
						dbSql.selectMapTile(superContext, "SELECT banklink FROM check_card WHERE name = '" 
								+ BDUtil.getApostrophe(beforesmsData.getName()) + "';", new ParseSelectData()
						{
							@Override
							public void resultData(Cursor c)
							{
								linkId = -1;
								
								int banklinkIndex = c.getColumnIndex("banklink");
								
								c.moveToFirst();
								
								for (int i = 0; i < c.getCount(); i++)
								{
									linkId = c.getInt(banklinkIndex);
									c.moveToNext();
								}
							}
						});
						
						if (linkId > -1)
						{
							dbSql.selectMapTile(superContext, "SELECT money FROM bankbook WHERE id = " + linkId + ";", new ParseSelectData()
							{
								@Override
								public void resultData(Cursor c)
								{
									BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getOutmoney()));
									
									int moneyIndex = c.getColumnIndex("money");
									
									c.moveToFirst();
									BigDecimal money = BigDecimal.ZERO;
									for (int i = 0; i < c.getCount(); i++)
									{
										money = money.add(new BigDecimal(c.getString(moneyIndex)));
										c.moveToNext();
									}
									
									money = money.subtract(tempMoney);
									
									HashMap<String, String> map = new HashMap<String, String>();
									map.put("money", money.toString());
									String [] whereArgs = new String[]{linkId + ""};
									dbSql.update(superContext, "bankbook", map, "id = ?", whereArgs);
								}
							});
						}
					}
				}
			}
			else if (beforesmsData.getMoneyType() == BDConstents.BANK_TYPE)
			{
				// 통장 현금 입금
				if (beforesmsData.getType() == BDConstents.OUTIN_TYPE)
				{
//					dbSql.selectMapTile(this, "SELECT money FROM bankbook WHERE name = '" 
//								+ beforesmsData.getName() + "';", new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getInmoney()));
//							int moneyIndex = c.getColumnIndex("money");
//							
//							c.moveToFirst();
//							BigDecimal dbMoney = BigDecimal.ZERO;
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
//								c.moveToNext();
//							}
//							
//							dbMoney = dbMoney.add(tempMoney);
//							
//							HashMap<String, String> map = new HashMap<String, String>();
//							map.put("money", dbMoney.toString());
//							String [] whereArgs = new String[]{beforesmsData.getName()};
//							dbSql.update(superContext, "bankbook", map, "name = ?", whereArgs);
//						}
//					});
//					
//					dbSql.selectMapTile(this, "SELECT money FROM real_money", new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getOutmoney()));
//							int moneyIndex = c.getColumnIndex("money");
//							
//							c.moveToFirst();
//							BigDecimal dbMoney = BigDecimal.ZERO;
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
//								c.moveToNext();
//							}
//							
//							dbMoney = dbMoney.subtract(tempMoney);
//							
//							HashMap<String, String> map = new HashMap<String, String>();
//							map.put("money", dbMoney.toString());
//							dbSql.update(superContext, "real_money", map, null, null);
//						}
//					});
				}
				// 통장 현금 출금
				else if (beforesmsData.getType() == BDConstents.INOUT_TYPE)
				{
//					dbSql.selectMapTile(this, "SELECT money FROM bankbook WHERE name = '" 
//								+ beforesmsData.getName() + "';", new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getOutmoney()));
//							int moneyIndex = c.getColumnIndex("money");
//							
//							c.moveToFirst();
//							BigDecimal dbMoney = BigDecimal.ZERO;
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
//								c.moveToNext();
//							}
//							
//							dbMoney = dbMoney.subtract(tempMoney);
//							
//							HashMap<String, String> map = new HashMap<String, String>();
//							map.put("money", dbMoney.toString());
//							String [] whereArgs = new String[]{beforesmsData.getName()};
//							dbSql.update(superContext, "bankbook", map, "name = ?", whereArgs);
//						}
//					});
//					
//					dbSql.selectMapTile(this, "SELECT money FROM real_money", new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getInmoney()));
//							int moneyIndex = c.getColumnIndex("money");
//							
//							c.moveToFirst();
//							BigDecimal dbMoney = BigDecimal.ZERO;
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
//								c.moveToNext();
//							}
//							
//							dbMoney = dbMoney.add(tempMoney);
//							
//							HashMap<String, String> map = new HashMap<String, String>();
//							map.put("money", dbMoney.toString());
//							dbSql.update(superContext, "real_money", map, null, null);
//						}
//					});
				}
				else
				{
					// 통장 입금
					if (beforesmsData.getOutmoney().equalsIgnoreCase("0"))
					{
						dbSql.selectMapTile(superContext, "SELECT money FROM bankbook WHERE name = '" 
								+ BDUtil.getApostrophe(beforesmsData.getName()) + "';", new ParseSelectData()
						{
							@Override
							public void resultData(Cursor c)
							{
								BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getInmoney()));
								
								int moneyIndex = c.getColumnIndex("money");
								
								c.moveToFirst();
								BigDecimal money = BigDecimal.ZERO;
								for (int i = 0; i < c.getCount(); i++)
								{
									money = money.add(new BigDecimal(c.getString(moneyIndex)));
									c.moveToNext();
								}
								
								money = money.add(tempMoney);
								
								HashMap<String, String> map = new HashMap<String, String>();
								map.put("money", money.toString());
								String [] whereArgs = new String[]{beforesmsData.getName()};
								dbSql.update(superContext, "bankbook", map, "name = ?", whereArgs);
							}
						});
					}
					// 통장 출금
					else
					{
						dbSql.selectMapTile(superContext, "SELECT money FROM bankbook WHERE name = '" 
								+ BDUtil.getApostrophe(beforesmsData.getName()) + "';", new ParseSelectData()
						{
							@Override
							public void resultData(Cursor c)
							{
								BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(beforesmsData.getOutmoney()));
								
								int moneyIndex = c.getColumnIndex("money");
								
								c.moveToFirst();
								BigDecimal money = BigDecimal.ZERO;
								for (int i = 0; i < c.getCount(); i++)
								{
									money = money.add(new BigDecimal(c.getString(moneyIndex)));
									c.moveToNext();
								}
								
								money = money.subtract(tempMoney);
								
								HashMap<String, String> map = new HashMap<String, String>();
								map.put("money", money.toString());
								String [] whereArgs = new String[]{beforesmsData.getName()};
								dbSql.update(superContext, "bankbook", map, "name = ?", whereArgs);
							}
						});
					}
				}
			}
			
			String balanceType = "";
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			if (beforesmsData.getMoneyType().equals(BDConstents.CREDIT_TYPE))
			{
				if (beforesmsData.getType() == BDConstents.INOUT_TYPE)
				{
					continue;
//					map.put("linktype", beforesmsData.getMoneyType());
//					map.put("category", BDConstents.BANK_TO_REAL);
//					map.put("postmoney", BDUtil.getCommaDel(beforesmsData.getPostmoney()));
//					map.put("inmoney", BDUtil.getCommaDel(beforesmsData.getPostmoney()));
				}
				else
				{
					map.put("linktype", beforesmsData.getMoneyType());
					map.put("category", BDConstents.CATEGORY_USE_CARD);
					map.put("postmoney", BDUtil.getCommaDel(beforesmsData.getPostmoney()));
				}
				
				balanceType = BDConstents.CREDIT_TYPE;
			}
			else if (beforesmsData.getMoneyType().equalsIgnoreCase(BDConstents.CHECK_TYPE))
			{
				if (beforesmsData.getType() == BDConstents.OUTIN_TYPE)
				{
					continue;
//					map.put("linktype", beforesmsData.getMoneyType());
//					map.put("category", BDConstents.REAL_TO_BANK);
//					map.put("outmoney", BDUtil.getCommaDel(beforesmsData.getOutmoney()));
//					map.put("inmoney", BDUtil.getCommaDel(beforesmsData.getInmoney()));
				}
				else if (beforesmsData.getType() == BDConstents.INOUT_TYPE)
				{
					continue;
//					map.put("linktype", beforesmsData.getMoneyType());
//					map.put("category", BDConstents.BANK_TO_REAL);
//					map.put("outmoney", BDUtil.getCommaDel(beforesmsData.getOutmoney()));
//					map.put("inmoney", BDUtil.getCommaDel(beforesmsData.getInmoney()));
				}
				else
				{
					if (beforesmsData.getOutmoney().equalsIgnoreCase("0"))
					{
						map.put("category", BDConstents.CATEGORY_IN_CARD);
						map.put("inmoney", BDUtil.getCommaDel(beforesmsData.getInmoney()));
					}
					else
					{
						map.put("category", BDConstents.CATEGORY_USE_CARD);
						map.put("outmoney", BDUtil.getCommaDel(beforesmsData.getOutmoney()));
					}
				}
				
				balanceType = BDConstents.CHECK_TYPE;
			}
			else if (beforesmsData.getMoneyType().equalsIgnoreCase(BDConstents.BANK_TYPE))
			{
				if (beforesmsData.getType() == BDConstents.OUTIN_TYPE)
				{
					continue;
//					map.put("linktype", beforesmsData.getMoneyType());
//					map.put("category", BDConstents.REAL_TO_BANK);
//					map.put("outmoney", BDUtil.getCommaDel(beforesmsData.getOutmoney()));
//					map.put("inmoney", BDUtil.getCommaDel(beforesmsData.getInmoney()));
				}
				else if (beforesmsData.getType() == BDConstents.INOUT_TYPE)
				{
					continue;
//					map.put("linktype", beforesmsData.getMoneyType());
//					map.put("category", BDConstents.BANK_TO_REAL);
//					map.put("outmoney", BDUtil.getCommaDel(beforesmsData.getOutmoney()));
//					map.put("inmoney", BDUtil.getCommaDel(beforesmsData.getInmoney()));
				}
				else
				{
					if (beforesmsData.getOutmoney().equalsIgnoreCase("0"))
					{
						map.put("category", BDConstents.CATEGORY_IN_BANK);
						map.put("inmoney", BDUtil.getCommaDel(beforesmsData.getInmoney()));
					}
					else
					{
						map.put("category", BDConstents.CATEGORY_OUT_BANK);
						map.put("outmoney", BDUtil.getCommaDel(beforesmsData.getOutmoney()));
					}
				}
				
				balanceType = BDConstents.BANK_TYPE;
			}
			
			map.put("date", beforesmsData.getDate());
			map.put("moneykind", beforesmsData.getName());
			map.put("type", beforesmsData.getType());
			map.put("memo", beforesmsData.getMemo());
			
			dbSql.insert(this, map, "in_out");
			
			if (!balanceType.equals(""))
			{
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setBalance(balanceType, beforesmsData.getName());
			}
		}
	}
	
	private class BeforesmsAdapter extends ArrayAdapter<BeforeSmsData>
	{
		Context context;
		int textViewId;
		ArrayList<BeforeSmsData> list;

		public BeforesmsAdapter(Context context, int textViewResourceId, ArrayList<BeforeSmsData> list) 
		{
			super(context, textViewResourceId, list);
			
			this.context = context;
			this.textViewId = textViewResourceId;
			this.list = list;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) 
		{
			View v = convertView;
			
			if (v == null)
			{
				LayoutInflater li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v  = li.inflate(textViewId, null);
			}
			
			BeforeSmsData data = list.get(position);
			
			TextView textDate = (TextView)v.findViewById(R.id.beforesmsListItem_textDate);
			TextView textName = (TextView)v.findViewById(R.id.beforesmsListItem_textName);
			TextView textMemo = (TextView)v.findViewById(R.id.beforesmsListItem_textMemo);
			TextView textMoney = (TextView)v.findViewById(R.id.beforesmsListItem_textMoney);
			
			textDate.setText(data.getDate());
			textName.setText(data.getName());
			textMemo.setText(data.getMemo());
			
			if (data.getType().equals(BDConstents.CREDIT_TYPE))
			{
				textMoney.setText("-" + BDUtil.getWon(data.getPostmoney()));
				textMoney.setTextColor(postMoneyColor);
			}
			else if (data.getInmoney().equals("0"))
			{
				textMoney.setText("-" + BDUtil.getWon(data.getOutmoney()));
				textMoney.setTextColor(outMoneyColor);
			}
			else
			{
				textMoney.setText("+" + BDUtil.getWon(data.getInmoney()));
				textMoney.setTextColor(inMoneyColor);
			}
			
			return v;
		}
	}

	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(superContext);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 0)
				{
					setDataSetting();
					
					if ( ! autosmsFlag)
					{
						return -2;
					}
					
					return arg0[1];
				}
				
				else if (arg0[1] == 1)
				{
					try
					{
						dbSql.beginTansaction(superContext);
						
						insertInOutTable();
						
						dbSql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							dbSql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				return -1;
			}
			else
			{
				return -1;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.showDialogFinish(superContext, "오류", "데이터를 가져오는데 실패 하였습니다.");
			}
			else if (result == -2)
			{
				BDUtil.showDialogFinish(superContext, "오류", " 등록된 문자자동화 내역이 없습니다. 먼저 문자자동화를 등록해주세요.");	
			}
			else if (result == 0) 
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				if (listViewBeforesms.getFooterViewsCount() > 0)
				{
					listViewBeforesms.removeFooterView(resultView);
				}
				
				if (beforesmsList.size() < 1)
				{
					listViewBeforesms.addFooterView(resultView);
					listViewBeforesms.setFooterDividersEnabled(false);
					listViewBeforesms.setOnItemClickListener(null);
				}
				else
				{
					//listViewBeforesms.setSelected(true);
					//listViewBeforesms.setOnItemClickListener(onItemClickListener);
					listViewBeforesms.setFooterDividersEnabled(true);
				}
				
				BeforesmsAdapter adapter = new BeforesmsAdapter(superContext, R.layout.beforesms_list_item, beforesmsList);
				listViewBeforesms.setAdapter(adapter);
				adapter.notifyDataSetChanged();
			}
			else if (result == 1)
			{
				BDUtil.showDialogFinish(superContext, "입력완료", beforesmsList.size() + "건의 문자를 입력했습니다.");
			}
		}
	}
	
	@Override
	protected void tipButton() {
		
	}
	
}
